package com.zhilong;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class WebTask extends AsyncTask<String, Void, String> 
{
	private Context cxt = null;
	
	WebTask(Context cxt)
	{
		super();
		this.cxt = cxt;
	}
	
	@Override
    protected String doInBackground(String... args) {
		String response = "";
        DefaultHttpClient client = new DefaultHttpClient();
        HttpRequestBase request = null;
        
        String url = args.length > 0 ? args[0] : "";
        try {
            if(args.length <= 1)
            	request = new HttpGet(url);
            else
            {
            	request = new HttpPost(url);
            	int paramCount = (args.length-1)/2; 
            	List<NameValuePair> params = new ArrayList<NameValuePair>();
            	for(int i = 0; i < paramCount; i++)
            		params.add(new BasicNameValuePair(args[1+i*2], args[(i+1)*2]));
            	((HttpPost)request).setEntity(new UrlEncodedFormEntity(params));
            }
            
            
            Log.i(getClass().getName(), "Accessing url " + url);
            String sessionId = SessionMgr.getCurrentSession().getId(); 
    		if(null != sessionId){
    			request.setHeader("Cookie", "JSESSIONID=" + sessionId);
            }
    		
          HttpResponse execute = client.execute(request);
			
          if(sessionId == null)
          {
              CookieStore mCookieStore = ((DefaultHttpClient)client).getCookieStore();
              List<Cookie> cookies = mCookieStore.getCookies();
              for (int i = 0; i < cookies.size(); i++) {
                    if ("JSESSIONID".equals(cookies.get(i).getName())) {
                    	SessionMgr.getCurrentSession().setId(cookies.get(i).getValue());
                        break;
                    }
                }
          }
          
            InputStream content = execute.getEntity().getContent();

            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
            	response += s;
          }

        } catch (Exception e) {
            Log.e(getClass().getName(), "Failed due to " + e);
        }
        
        Log.d(getClass().getName(), "Response: " + response);
      return response;
    }

	protected void onPostExecute(String result) 
	{
		Log.d(getClass().getName(), "Result of task: " + result);
		if("LOGINREQUIRED".equals(result))
		{
			cxt.startActivity(new Intent(cxt, Login.class));
		}
    }
}

